<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
		//用户添加
   public function getAdd(){
   		//显示模板
   		return view('admin.user.add');

   }
   	//用户插入
   public function postInsert(Request $request){
   		//处理数据

   		$arr = array();
   		$arr = $request->except('_token','repassword');
   		$arr['token']=str_random(50);
   		
   		$arr['createTime']=date('Y-m-d H:i:s',time());
   		$arr['password']=Hash::make($arr['password']);
   		//验证数据
   		// if(!$arr['username']){
   		// 	return redirect('/admin/user/add')->with('error','用户名必填');
   		// }
   		//laravel表单验证
   		$this->validate($request,[
   			'username'=>'required',
   			'password'=>'required',
   			'repassword'=>'required|same:password',
   			'email'=>'required|email',
   			'address'=>'required',
   		],[
   			'username.required'=>'用户名必填',
   			'password.required'=>'密码必填',
   			'repassword.required'=>'确认密码必填',
   			'repassword.same'=>'确认密码必须和密码一致',
   			'email.required'=>'邮箱必填',
   			'email.email'=>'邮箱格式不正确',
   			'address.required'=>'地址必填',
   			
   		]);

   		//插入数据
   		$res = DB::table('user')->insert($arr);
   		//判断结果
   		if($res){
   			return redirect('/admin/user/index')->with('success','插入成功');
   		}else{
   			return back()->with('error','插入失败');
   		}
   }
   //用户的列表页
   public function getIndex(Request $request){
   		$search = $request -> input('search');
   		
   		if(!empty($search)){
   			$data = DB::table('user')->where('username','like','%'.$search.'%')->orWhere('email','like','%'.$search.'%')->orWhere('sex','like','%'.$search.'%')->orderBy('id')->paginate(10);
   		}else{
			//查询数据 并且分页
   			$data = DB::table('user')->orderBy('id');

   		}
   		

   		return view('admin.user.index',['data'=>$data,'request'=>$request->all()]);
   }
   //用户删除操作
   public function getDelete($id){
   		//返回影响行数
   		$res = DB::table('user')->where('id',$id)->delete();
   		if($res>0){
   			return redirect('/admin/user/index')->with('success','删除成功');
   		}else{
   			return back()->with('error','删除失败');
   		}
   }
   //用户修改页
   public function getEdit($id){
   	$data = DB::table('user')->where('id',$id)->first();
   	 return view('admin.user.edit',['data'=>$data]);
   }
   //用户修改操作
   public function postUpdate($id,Request $request){
   		//接受信息
   		$data = $request->except('_token');
   		$res = DB::table('user')->where('id',$id)->update($data);
   		if($res>0){
   			return redirect('/admin/user/index')->with('success','修改成功');
   		}else{
   			return back()->with('error','修改失败');
   		}
   }
}
